﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommunicationProtocol.dto.game;

namespace CommunicationProtocol.dto.command.server
{
    public class CreatingPlantCommand : Command, IEnumerable<DynamicPlant>
    {
        public List<DynamicPlant> DynamicPlants;

        public CreatingPlantCommand(DynamicPlant baseObject): base(101) {

            DynamicPlants = new List<DynamicPlant>();
            DynamicPlants.Add(baseObject);
        }

        public CreatingPlantCommand(byte[] data) : base(101)
        {
            int count = BitConverter.ToInt32(data,0);

            DynamicPlants = new List<DynamicPlant>();
            for (int i = 4; i < count*5+4; i+=5)
            {
                short objectId = (short)((data[i] << 8) + data[i+1]);
                byte objectType = data[i+2];
                byte locationX = data[i+3];
                byte locationY = data[i+4];
                DynamicPlants.Add(
                    PlantFactory.fromObjectType(objectId, objectType, locationX, locationY)
                );
            }
            
            
            
           
        }

        public CreatingPlantCommand(List<DynamicPlant> allPlantsOnMap) : base(101)
        {
            this.DynamicPlants = allPlantsOnMap;
        }

        public override byte[] GetBytes()
        {
            IEnumerable<byte> result = new byte[]{functionCode}
                .Concat(BitConverter.GetBytes(DynamicPlants.Count));

            foreach (DynamicPlant plant in DynamicPlants)
            {

                result = result.Concat(new byte[]
                    {
                        (byte)((plant.ObjectId>>8)&0xff),
                        (byte)(plant.ObjectId&0xff),
                        plant.ObjectType,
                        plant.LocationX,
                        plant.LocationY
                    }
                );
            }

            return result.ToArray();

        }


        public IEnumerator<DynamicPlant> GetEnumerator()
        {
            return DynamicPlants.GetEnumerator();
        }


        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}
